<?php

/**
 * Name: 风险源控制器
 * User: Silent
 * Date: 2025-10-09
 * Time: 19:32:46
 */

namespace App\Http\Controllers\V1\Resources\Safety;

use App\Http\Controllers\Controller;
use App\Http\Requests\Safety\RiskSourceRequest;
use App\Repositories\Safety\RiskSourceRepository;
use App\Services\Safety\RiskSourceService;
use Illuminate\Http\Request;

class RiskSourceController extends Controller
{
    protected $service;

    protected $repository;

    public function __construct(RiskSourceService $service, RiskSourceRepository $repository)
    {
        $this->service    = $service;
        $this->repository = $repository;
    }

    /**
     *  列表.
     *
     * @param Request $request
     * @return array
     */
    public function list(Request $request)
    {

        $inputs = $request->all();
        $data   = $this->service->list($inputs);

        return $this->_success('请求成功', $data);
    }

    /**
     * 添加风险源.
     *
     * @param RiskSourceRequest $request
     * @return array
     */
    public function add(RiskSourceRequest $request)
    {
        $inputs = $request->validated();
        $result = $this->service->add($inputs);

        if ($result['success']) {
            return $this->_success($result['message'], $result['data'] ?? null);
        }

        return $this->_error($result['message']);
    }

    /**
     * 修改风险源.
     *
     * @param RiskSourceRequest $request
     * @return array
     */
    public function update(RiskSourceRequest $request)
    {
        $inputs = $request->validated();
        $result = $this->service->saveData($inputs);

        if ($result['success']) {
            return $this->_success($result['message'], $result['data'] ?? null);
        }

        return $this->_error($result['message']);
    }

    /**
     * 详情.
     *
     * @param int $id ID
     * @return array
     */
    public function detail($id)
    {
        if (empty($id)) {
            return $this->_error('ID不能为空');
        }

        $result = $this->service->detail($id);
        if ($result['success']) {
            return $this->_success($result['message'], $result['data']);
        }

        return $this->_error($result['message']);
    }

    /**
     *  删除.
     *
     * @param Request $request
     * @return array
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');
        if (empty($id)) {
            return $this->_error('ID不能为空');
        }

        $query = $this->repository->detail($id);
        if(empty($query)){
            return $this->_error('当前风险源不存在');
        }

        $result = $this->service->delete($query);
        if ($result['success']) {
            return $this->_success($result['message']);
        }

        return $this->_error($result['message']);
    }
}
